﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using MvcAtletIS.Models;
using System.IO;

namespace MvcAtletIS.Controllers
{
    public class ResultsController : Controller
    {
        atletisEntities db = new atletisEntities();
        
        // GET: /Results/
        public ActionResult Index(int selectedYear = 0, int selectedMonth = 0)
        {
            if (selectedYear == 0)
                selectedYear = DateTime.Now.Year;

            if (selectedMonth == 0)
                selectedMonth = DateTime.Now.Month;

            DateTime today = DateTime.Now.Date;
            ViewBag.ActualCompetitions = db.Competitions.Where(c => c.DateFrom <= today & c.DateTo >= today).ToList();
            ViewBag.NextCompetitions = db.Competitions.Where(c => c.DateFrom > today).OrderBy(c => c.DateFrom).Take(5).ToList();
            ViewBag.PreviousCompetitions = db.Competitions.Where(c => c.DateTo < today).OrderByDescending(c => c.DateFrom).Take(5).ToList();
            
            ViewBag.selectedYear = new SelectList(db.Years, "Year", "Year", selectedYear);
            ViewBag.selectedMonth = new SelectList(Months.GetMonths(), "ID", "Name", selectedMonth);

            var competitions = db.Competitions.Where(c => c.DateFrom.Value.Year == selectedYear & c.DateFrom.Value.Month == selectedMonth).OrderBy(c => c.DateFrom).ToList();
            return View(competitions);
        }

        public ActionResult Details(int competitionId)
        {
            var competitions = db.Competitions.Single(c => c.ID == competitionId);
            ViewBag.Competitions = competitions;
            
            string path = string.Format("~/Content/results/{0}/{1}/{2}.html", 
                competitions.DateFrom.Value.Year.ToString(), 
                competitions.DateFrom.Value.Month.ToString(), 
                competitionId.ToString());
            path = Server.MapPath(path);
            
            if (System.IO.File.Exists(path))
            {
                StreamReader sr = new StreamReader(path, System.Text.Encoding.GetEncoding("windows-1250"));
                string htmlContent = sr.ReadToEnd();

                ViewBag.MyHtmlContent = htmlContent;
            }
            else
            {
                ViewBag.MyHtmlContent = "Výsledky sa nenašli.";
            }

            return View();
        }



        

    }

    
}
